import { MemStatus, SystemInfo } from '@shared/models'
import { atom } from 'jotai'
import { unwrap } from 'jotai/utils'

const infoSystem: () => Promise<SystemInfo> = async () => {
  const res = await window.context.getSystemInfo()
  return res as SystemInfo
}

const infoSystemAtomAsync = atom<SystemInfo | Promise<SystemInfo>>(infoSystem())

export const infoSystemAtom = unwrap(infoSystemAtomAsync, (prev) => prev)

// 用于强制刷新监控数据的原子
export const monitorRefreshAtom = atom(0)

const memInfoAtomAsync = atom<MemStatus | Promise<MemStatus>>(async (get) => {
  get(monitorRefreshAtom) // 依赖刷新触发器
  const res = await window.context.getSystemMemUsed()
  return res as MemStatus
})

export const memInfoAtom = unwrap(memInfoAtomAsync, (prev) => prev)

const cpuInfoAtomAsync = atom<number | Promise<number>>(async (get) => {
  get(monitorRefreshAtom) // 依赖刷新触发器
  const res = await window.context.getSystemCpuUsed()
  return res as number
})

export const cpuInfoAtom = unwrap(cpuInfoAtomAsync, (prev) => prev)

const netWorkLoadAtomAsync = atom(async (get) => {
  get(monitorRefreshAtom) // 依赖刷新触发器
  // 间隔100毫秒获取网络流量数据，返回字节速率bytes/second
  const net1 = await window.context.getSystemNetworkLoad()
  await new Promise((resolve) => setTimeout(resolve, 500))
  const net2 = await window.context.getSystemNetworkLoad()
  const load: { rxRate: number; txRate: number } = {
    rxRate: (net2.rx - net1.rx) / 0.5, // bytes/second
    txRate: (net2.tx - net1.tx) / 0.5 // bytes/second
  }
  if (net1.rx == 0 && net1.tx == 0) return { rxRate: 0, txRate: 0 }
  return load
})

export const netWorkLoadAtom = unwrap(netWorkLoadAtomAsync, (prev) => prev)

// 刷新监控数据的写入原子
export const refreshMonitorData = atom(null, (get, set) => {
  set(monitorRefreshAtom, get(monitorRefreshAtom) + 1)
})
